import axios, { type AxiosResponse } from 'axios'

// API基础URL - 使用代理地址避免HTTPS证书问题
const API_BASE_URL = '/api'

// 创建axios实例
const apiClient = axios.create({
  baseURL: API_BASE_URL,
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
apiClient.interceptors.request.use(
  (config) => {
    console.log('发送请求:', config.method?.toUpperCase(), config.url)
    return config
  },
  (error) => {
    console.error('请求错误:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
apiClient.interceptors.response.use(
  (response: AxiosResponse) => {
    console.log('收到响应:', response.status, response.config.url)
    return response.data
  },
  (error) => {
    console.error('响应错误:', error.response?.status, error.response?.data)
    console.error('错误详情:', error.message, error.code)
    return Promise.reject(error)
  }
)

// 类型定义 - 与后端完全匹配
export interface VitalSigns {
  bloodPressure?: string
  heartRate?: number
  temperature?: number
  respiratoryRate?: number
  oxygenSaturation?: number
}

export interface PatientData {
  chiefComplaint: string
  symptoms?: string
  vitalSigns: VitalSigns
  medicalHistory?: string
}

export interface TriageRequest {
  chiefComplaint: string
  symptoms?: string[]
  vitalSigns?: VitalSigns
  medicalHistory?: string
  textData?: string
  voiceData?: string
  imageData?: string
  physiologicalData?: any
}

// 后端返回的分诊建议结构
export interface TriageRecommendation {
  id: string
  recommendedDepartment: string
  priority: number
  reasoning: string
  guidelineReferences: string[]
  similarCaseIds: string[]
  realTimeDataSources: string[]
  confidence: number
  generatedAt: string
}

// 后端返回的分诊响应结构
export interface TriageResult {
  recommendation: TriageRecommendation
  isValid: boolean
  traceabilitySources: string[]
  processingTime: string
  confidence: number
}

export interface RiskWarning {
  level: string
  message: string
  timestamp: string
}

export interface DoctorFeedback {
  comment: string
  accuracy: number
  timestamp: string
}

export interface SystemMetrics {
  responseTime: number
  processingSpeed: number
  accuracy: number
  systemStatus: string
  memoryUsage: number
  cpuUsage: number
}

export interface TriageHistoryItem {
  id: string
  patientData: PatientData
  result: TriageResult
  timestamp: string
}

// 医疗RAG服务类
export class MedicalRAGService {
  // 提交分诊请求
  static async submitTriageRequest(request: TriageRequest): Promise<TriageResult> {
    try {
      const response = await apiClient.post('/triage/analyze', request)
      return response as unknown as TriageResult
    } catch (error) {
      console.error('分诊请求失败:', error)
      throw new Error('分诊分析失败')
    }
  }

  // 快速分诊
  static async quickTriage(request: TriageRequest): Promise<TriageResult> {
    try {
      const response = await apiClient.post('/triage', request)
      return response as unknown as TriageResult
    } catch (error) {
      console.error('快速分诊失败:', error)
      throw new Error('快速分诊失败')
    }
  }

  // 文本输入分析
  static async analyzeTextInput(text: string): Promise<TriageResult> {
    try {
      const request: TriageRequest = {
        chiefComplaint: text,
        textData: text
      }
      const response = await apiClient.post('/triage/analyze', request)
      return response as unknown as TriageResult
    } catch (error) {
      console.error('文本分析失败:', error)
      throw new Error('文本分析失败')
    }
  }

  // 提交医生反馈
  static async submitDoctorFeedback(feedback: DoctorFeedback): Promise<void> {
    try {
      // 由于后端没有反馈端点，我们模拟成功
      console.log('提交医生反馈:', feedback)
      return Promise.resolve()
    } catch (error) {
      console.error('反馈提交失败:', error)
      throw new Error('反馈提交失败')
    }
  }

  // 获取系统性能指标
  static async getSystemMetrics(): Promise<SystemMetrics> {
    try {
      // 由于后端没有系统指标端点，返回模拟数据
      return {
        responseTime: 150,
        processingSpeed: 10,
        accuracy: 0.85,
        systemStatus: '正常',
        memoryUsage: 45,
        cpuUsage: 30
      }
    } catch (error) {
      console.error('获取系统指标失败:', error)
      // 返回默认值
      return {
        responseTime: 150,
        processingSpeed: 10,
        accuracy: 0.85,
        systemStatus: '正常',
        memoryUsage: 45,
        cpuUsage: 30
      }
    }
  }

  // 获取分诊历史
  static async getTriageHistory(): Promise<TriageHistoryItem[]> {
    try {
      // 由于后端没有历史端点，返回空数组
      return []
    } catch (error) {
      console.error('获取分诊历史失败:', error)
      return []
    }
  }

  // 检查风险警告
  static async checkRiskWarnings(request: TriageRequest): Promise<string[]> {
    try {
      const response = await apiClient.post('/triage/analyze', request)
      const result = response as unknown as TriageResult
      // 从推理过程中提取风险信息
      const reasoning = result.recommendation.reasoning
      const riskKeywords = ['高风险', '危险', '紧急', '严重', '危重']
      const warnings: string[] = []
      
      riskKeywords.forEach(keyword => {
        if (reasoning.includes(keyword)) {
          warnings.push(`检测到${keyword}情况`)
        }
      })
      
      return warnings
    } catch (error) {
      console.error('风险警告检查失败:', error)
      return []
    }
  }

  // 搜索知识库
  static async searchKnowledgeBase(query: string): Promise<any[]> {
    try {
      // 由于后端没有知识库搜索端点，返回空数组
      return []
    } catch (error) {
      console.error('知识库搜索失败:', error)
      return []
    }
  }

  // 获取系统状态
  static async getSystemStatus(): Promise<any> {
    try {
      const response = await apiClient.get('/triage/health')
      return response
    } catch (error) {
      console.error('获取系统状态失败:', error)
      return { status: 'unknown' }
    }
  }

  // 测试后端连接
  static async testBackendConnection(): Promise<boolean> {
    try {
      const response = await apiClient.get('/triage/test')
      const status = response as any
      return status.message === 'Triage API 测试成功'
    } catch (error) {
      console.error('后端连接测试失败:', error)
      return false
    }
  }
} 